package com.module.boots.api.exception;

import java.util.List;
import java.util.Map;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.google.common.collect.Maps;
import com.module.boots.api.message.ResponseMsg;
import com.module.boots.api.utils.MsgUtils;
import com.module.boots.exception.CommonRuntimeException;

/**
 * 统一异常处理
 * @author：溪云阁
 * @date：2020年5月2日
 */
@RestControllerAdvice
public class CommonExceptionHandler {

    /**
     * 对错误信息进行处理
     * @author 溪云阁
     * @param e 拦截到的错误信息
     * @return
     * @throws Exception ResponseMsg<Object>
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseMsg<Object> commonErrorHandler(Exception e) throws Exception {
        System.out.println("进入到异常测试");
        ResponseMsg<Object> msg = new ResponseMsg<>();
        if (e instanceof CommonRuntimeException) {
            final CommonRuntimeException common = (CommonRuntimeException) e;
            msg = MsgUtils.buildFailureMsg(common.getMessage());
        } else if (e instanceof MethodArgumentNotValidException) {
            final MethodArgumentNotValidException valid = (MethodArgumentNotValidException) e;
            msg = MsgUtils.buildFailureMsg(buildParamError(valid.getBindingResult()));
        } else {
            msg = MsgUtils.buildFailureMsg(e.getMessage());
        }
        return msg;
    }

    /**
     * 构建参数错误
     * @author 溪云阁
     * @param result
     * @return JSONObject
     */
    private Map<String, Object> buildParamError(BindingResult result) {
        final Map<String, Object> map = Maps.newConcurrentMap();
        if (result.hasErrors()) {
            final List<FieldError> errors = result.getFieldErrors();
            for (final FieldError error : errors) {
                map.put(error.getField(), error.getDefaultMessage());
            }
        }
        return map;
    }
}
